package com.web.graduationpro.manager.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.web.graduationpro.dao.service.InstrumentSchoolService;
import com.web.graduationpro.dao.service.TeacherService;
import com.web.graduationpro.model.InstrumentSchool;
import com.web.graduationpro.model.Teacher;

@Controller
@RequestMapping("/manager/teacher/*")
public class ManagerTeacherController {

	@Resource(name="instrumentSchoolServiceImpl")
	private InstrumentSchoolService instrumentSchoolServiceImpl;
	
	@Resource(name="teacherServiceImpl")
	private TeacherService teacherServiceImpl;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)  
    public String index() {  
        return "/manager/teacher/index";
    } 
	
	@RequestMapping(value = "getTeacher", method = RequestMethod.POST)  
    public void  getData(HttpServletRequest request,HttpServletResponse reponse) { 
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		int startNum = 0;
		int pageNum = 10;
		String start = request.getParameter("start");
		if(start!=null && !"".equals(start.trim())){
			startNum = Integer.parseInt(start);
		}
		String pageSize = request.getParameter("pageSize");
        if(pageSize!=null && !"".equals(pageSize.trim())){
        	pageNum = Integer.parseInt(pageSize);
		}
        
        String queryHql = "  FROM Teacher tc WHERE tc.id!=0";
        String queryCountHql = "SELECT count(*) From Teacher tc WHERE tc.id!=0 ";
        List<Object> searchValues = new ArrayList<Object>();
        String keyword = request.getParameter("keyword");
        if(keyword!=null && !"".equals(keyword.trim())){
        	searchValues.add("%"+keyword+"%");
        	queryHql += " AND tc.name like ?";
        	queryCountHql += " AND tc.name like ?";
        }
      
        List<Teacher> datas = null;
        
        Object[] cses = null;
        if(searchValues!=null && searchValues.size()!=0){
        	cses = new Object[searchValues.size()];
        	for(int i=0;i<searchValues.size();i++){
        		cses[i] = searchValues.get(i);
        	}
        	datas = teacherServiceImpl.findByPage(queryHql, cses , startNum, pageNum);
        }else{
    		datas = teacherServiceImpl.findByPage(queryHql, startNum, pageNum);	
        }
		
		String result = "";
		if(datas!=null && datas.size()!=0){
			List<Teacher> returnResultList = new ArrayList<Teacher>();
			for(Teacher tc:datas){
				if(tc.getHeadimg()!=null && !"".equals(tc.getHeadimg())){
					tc.setHeadimg("<img src='../../upload/"+tc.getHeadimg()+"' border='0' style='width:50px;height:50px;'/>");
				}
				tc.setSsSchool(tc.getInstrumentSchool().getSchoolName());
				returnResultList.add(tc);
			}
			JsonConfig jc = new JsonConfig();
			jc.setExcludes(new String[]{"instrumentSchool"});
			JSONArray json = JSONArray.fromObject(returnResultList,jc);
			result = json.toString();
		}
		
		int count = 0;
		 if(searchValues!=null && searchValues.size()!=0){
			 count = teacherServiceImpl.findTotalCount(queryCountHql, cses);
		 }else{
			 count = teacherServiceImpl.findTotalCount(Teacher.class);
		 }
		 String str = "{\"total\":" + count + ",\"rows\":" + result.toString() + "}";
         if("".equals(result.trim())){
        	 str = "{\"total\":0,\"rows\":[]}";
         }
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)  
    public void saveOrUpdate(MultipartHttpServletRequest request,HttpServletResponse reponse) { 
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		int handle = 0;
		String id = request.getParameter("id");
		Teacher teacher = null;
		if(id!=null && !"".equals(id.trim())){
			teacher = (Teacher) teacherServiceImpl.findById(Teacher.class, Integer.parseInt(id));
			handle = 1;
		}else{
			teacher = new Teacher();
		}
		
		 List<MultipartFile> files = request.getFiles("file");  
		 if(files!=null && files.size()!=0){
	         for( int i=0; i<files.size() ;i++){  
	              if(! files.get(i).isEmpty()) {  
	            	  MultipartFile myfile = files.get(i);
	                  String realPath = request.getSession().getServletContext().getRealPath("/upload"); 
	                  String fileName = myfile.getOriginalFilename();
	                  
	                  Date uploadNowDate = new Date();
	          		  DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"+(i+1));
	          		  String nowFileName = dateFormat.format(uploadNowDate)+fileName.substring(fileName.lastIndexOf("."));
	                  try {
	 					FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, nowFileName));
	 				  } catch (IOException e) {
	 					 e.printStackTrace();
	 				 }  
	                  if(i==0){
	                	  teacher.setHeadimg(nowFileName);
	                	  break;
	                  }
	              }  
	         }   
		 }
		
		String name = request.getParameter("name");
		String ssSchool = request.getParameter("ssSchool");
		String tdescribe = request.getParameter("tdescribe");
		
		teacher.setName(name);
		InstrumentSchool is = (InstrumentSchool)instrumentSchoolServiceImpl.findById(InstrumentSchool.class, Integer.parseInt(ssSchool));
		if(is!=null){
			teacher.setInstrumentSchool(is);
		}
		teacher.setTdescribe(tdescribe);
		
		String registerStatus = "error";
		try{
			if(handle==0){
				teacherServiceImpl.save(teacher);
			}else if(handle==1){
				teacherServiceImpl.updata(teacher);
			}
			registerStatus = "success";
		}catch(Exception e){
			e.printStackTrace();
		}

		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(registerStatus);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    } 
	
	@RequestMapping(value = "delete", method = RequestMethod.POST)  
    public void  delete(HttpServletRequest request,HttpServletResponse reponse) { 
		String deleteids = request.getParameter("deleteids");
		String result = "error";
		if(deleteids!=null && !"".equals(deleteids.trim())){
			 String[] deleteIdSplit = deleteids.split(",");
			 String hql = "";
			 for(int i=0;i<deleteIdSplit.length;i++){
				if(!"".equals(deleteIdSplit[i].trim())){
					 if(i==0) {
						 hql = "DELETE FROM Teacher where id="+deleteIdSplit[i];
					  } else {
						 hql =hql + " or id="+deleteIdSplit[i];
					  }
				}
			 }

			 if(!"".equals(hql.trim())){
				 int deleteResult = teacherServiceImpl.delete(hql);
				 if(deleteResult>0){
					result = "success";
				 } 
			 }
		}
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
